import { taskpool } from "@kit.ArkTS";

/**
 * 排序工具类
 */
export class SortUtil {
  /**
   * 升序排序
   * @param arr 数组
   * @param sortField 排序字段名
   * @returns
   */
  async asc<T>(arr: T[], sortField: string): Promise<T[]> {
    let task = new taskpool.Task(sort, arr, sortField, true)
    let result = await taskpool.execute(task) as T[]
    return result
  }

  /**
   * 降序排序
   * @param arr 数组
   * @param sortField 排序字段名
   * @returns
   */
  async desc<T>(arr: T[], sortField: string): Promise<T[]> {
    let task = new taskpool.Task(sort, arr, sortField, false)
    let result = await taskpool.execute(task) as T[]
    return result
  }
}

/**
 * 排序
 * @param arr
 * @param sortField
 * @param isAsc
 * @returns
 */
function sort<T>(arr: T[], sortField: string, isAsc: boolean): T[] {
  'use concurrent'
  return arr.sort((a: T, b: T) => {
    let left = a[sortField], right = b[sortField];
    if (typeof left == 'string') {
      if (isAsc) {
        return Number.parseFloat(left) - Number.parseFloat(right);
      } else {
        return Number.parseFloat(right) - Number.parseFloat(left);
      }
    }
    if (isAsc) {
      return left - right;
    } else {
      return right - left;
    }
  })
}

let sortUtil = new SortUtil();
export default sortUtil;